package com.mingtu.guards.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.center.adapter.DepartStaffAdapter2;
import com.mingtu.center.adapter.LeaderDepartmentAdapter;
import com.mingtu.center.bean.DepartStaffBean;
import com.mingtu.center.bean.DeptNameBean;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.decoration.BottomSpaceItemDecoration;
import com.mingtu.common.decoration.TopSpaceItemDecoration;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.CalendarPickerUtils;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.UIUtils;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.guards.R;
import com.mingtu.guards.adapter.AllRecordReportAdapter;
import com.mingtu.guards.base.MyBaseActivity;
import com.mingtu.guards.bean.AllReportRecordBean;
import com.mingtu.guards.utils.MyConstant;
import com.mingtu.guards.view.FilterCancleView;
import com.mingtu.guards.view.FilterSureView;
import com.mingtu.guards.view.TimeFilterView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.mingtu.guards.utils.MyConstant.animationType;
import static com.mingtu.guards.utils.MyConstant.isFirstOnly;
import static com.mingtu.guards.utils.MyConstant.isOpenLoadAnimation;

public class ReportRecordActivity extends MyBaseActivity {

    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.srl_up)
    SmartRefreshLayout srlUp;
    @BindView(R.id.tv_fold_depart)
    TextView tvFoldDepart;
    @BindView(R.id.iv_arrow)
    ImageView ivArrow;
    @BindView(R.id.layout_arrow_depart)
    LinearLayout layoutArrowDepart2;
    @BindView(R.id.layout_depart)
    RelativeLayout layoutDepart;
    @BindView(R.id.recycler_depart)
    RecyclerView recyclerDepart;
    @BindView(R.id.tv_fold_people)
    TextView tvFoldPeople;
    @BindView(R.id.iv_arrow2)
    ImageView ivArrow2;
    @BindView(R.id.layout_arrow_people)
    LinearLayout layoutArrowPeople;
    @BindView(R.id.layout_people)
    RelativeLayout layoutPeople;
    @BindView(R.id.recycler_people)
    RecyclerView recyclerPeople;
    @BindView(R.id.layout_right_drawer)
    RelativeLayout layoutRightDrawer;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @BindView(R.id.time_filter_time)
    TimeFilterView timeFilterTime;
    @BindView(R.id.filter_cancle_view)
    FilterCancleView filterCancleView;
    @BindView(R.id.filter_sure_view)
    FilterSureView filterSureView;

    private int currentPage = 1;
    private boolean isLoadMore = true;
    private boolean departFlag = false; //记录部门是否展开
    private boolean peopleFlag = false; //记录人员是否展开
    private String beginTime = null;
    private String endTime = null;

    private AllRecordReportAdapter allRecordReportAdapter;
    private DeptNameBean deptNameBean2;
    private List<DeptNameBean.ListBean> departBeans2;
    private List<DeptNameBean.ListBean> myDepartBeans2;

    private List<DepartStaffBean.ListBean> departStaffBeans;
    private List<DepartStaffBean.ListBean> myDepartStaffBeans;
    private DepartStaffAdapter2 departStaffAdapter;
    private LeaderDepartmentAdapter leaderDepartmentAdapter;
    private String checkName;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_report_record;
    }

    @Override
    protected void initView() {
        setModuleTitle("上报记录");
        setTitleBarBackground(getResources().getDrawable(com.mingtu.center.R.drawable.titlebar_line_bottom));
        showTopRightImg(R.mipmap.icon_filte);
    }

    @Override
    protected void initData() {
        LinearLayoutManager manager1 = new LinearLayoutManager(context);
        recycler.setLayoutManager(manager1);
        recycler.addItemDecoration(new TopSpaceItemDecoration());
        recycler.addItemDecoration(new BottomSpaceItemDecoration());

        allRecordReportAdapter = new AllRecordReportAdapter();

        if (isOpenLoadAnimation) {
            allRecordReportAdapter.isFirstOnly(isFirstOnly);
            allRecordReportAdapter.openLoadAnimation(animationType);
        }

        allRecordReportAdapter.setEmptyView(new EmptyDataLayout(context));

        recycler.setAdapter(allRecordReportAdapter);
        allRecordReportAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                int eventId = allRecordReportAdapter.getData().get(position).getId();
                Bundle bundle = new Bundle();
                bundle.putString("eventId", eventId + "");
                IntentUtils.getInstance().readyGo(ActivityUtil.getTopActivity(), ReportedDetailsActivity.class, bundle);
            }
        });

        //部门列表
        FlexboxLayoutManager flm2 = new FlexboxLayoutManager(this);
        flm2.setFlexWrap(FlexWrap.WRAP);
        flm2.setFlexDirection(FlexDirection.ROW);
        flm2.setAlignItems(AlignItems.STRETCH);
        flm2.setJustifyContent(JustifyContent.FLEX_START);
        recyclerDepart.setLayoutManager(flm2);

        leaderDepartmentAdapter = new LeaderDepartmentAdapter(context, null);
        recyclerDepart.setAdapter(leaderDepartmentAdapter);
        leaderDepartmentAdapter.setOnItemClickListener(new LeaderDepartmentAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                leaderDepartmentAdapter.checked(position);

                String deptId = deptNameBean2.getList().get(position).getDeptId() + "";
                getPeopleList(deptId);

                //恢复人员名称的初始值
                peopleFlag = false;
                tvFoldPeople.setText("展开");
            }
        });

        //部门人员列表
        FlexboxLayoutManager flm3 = new FlexboxLayoutManager(this);
        flm3.setFlexWrap(FlexWrap.WRAP);
        flm3.setFlexDirection(FlexDirection.ROW);
        flm3.setAlignItems(AlignItems.STRETCH);
        flm3.setJustifyContent(JustifyContent.FLEX_START);
        recyclerPeople.setLayoutManager(flm3);


        departStaffAdapter = new DepartStaffAdapter2(context, null);
        recyclerPeople.setAdapter(departStaffAdapter);
        departStaffAdapter.setOnItemClickListener(new DepartStaffAdapter2.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int i) {
                departStaffAdapter.checked(i);
            }
        });

        timeFilterTime.setOnTimeResultListener(new TimeFilterView.OnTimeResultListener() {
            @Override
            public void onResult(Date startDate, Date endDate) {
                beginTime = UIUtils.getTime3(startDate);
                endTime = UIUtils.getTime3(endDate);
            }
        });

        filterCancleView.setOnClickListener(new FilterCancleView.OnClickListener() {
            @Override
            public void onClickCancel() {
                closeDrawers();
            }
        });

        filterSureView.setOnClickListener(new FilterSureView.OnClickListener() {
            @Override
            public void onClickReset() {
                closeDrawers();
                resetData();
                CalendarPickerUtils.getInstance().resetData();
            }

            @Override
            public void onClickSure() {
                closeDrawers();
                checkName = departStaffAdapter.getCheckName();
                getReportRecord(1);
            }
        });


    }

    @Override
    protected void getData() {
        initListener();
        getReportRecord(1);
        getDeptList2();
    }

    private void initListener() {
        initPullRefresh();//刷新
        initLoadMoreListener();//加载更多
    }

    private void initPullRefresh() {
        srlUp.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
        srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                srlUp.finishRefresh(Constant.REFRESH_TIME);
                srlUp.setNoMoreData(false);
                currentPage = 1;
                getReportRecord(1);
            }
        });
    }

    private void initLoadMoreListener() {
        srlUp.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isLoadMore) {
                    currentPage = MyUtills.loadPage(allRecordReportAdapter.getData(), Constant.PAGE_SIZE);
                    getReportRecord(currentPage);
                }
                srlUp.finishLoadMore(Constant.LOADMORE_TIME);
            }
        });

    }

    @Override
    protected void onClickTitlebarRight(View view) {
        super.onClickTitlebarRight(view);
        boolean isOpen = drawerLayout.isDrawerOpen(layoutRightDrawer);
        if (isOpen) {
            closeDrawers();
        } else {
            openDrawer();
        }
    }

    @OnClick({R.id.layout_arrow_people, R.id.layout_arrow_depart})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_arrow_depart:
                if (departFlag) { //默认为false,收起状态
                    departFlag = false;
                    tvFoldDepart.setText("展开");
                    leaderDepartmentAdapter.upData(myDepartBeans2);
                } else {
                    departFlag = true;
                    tvFoldDepart.setText("收起");
                    leaderDepartmentAdapter.upData(departBeans2);
                }
                break;
            case R.id.layout_arrow_people:
                if (peopleFlag) { //默认为false,收起状态
                    peopleFlag = false;
                    tvFoldPeople.setText("展开");
                    departStaffAdapter.upData(myDepartStaffBeans);
                } else {
                    peopleFlag = true;
                    tvFoldPeople.setText("收起");
                    departStaffAdapter.upData(departStaffBeans);
                }
                break;
        }

    }

    private void resetData() {
        departStaffAdapter.resetData();
        beginTime = null;
        beginTime = null;
        checkName = null;
        timeFilterTime.resetData();
        getReportRecord(1);
    }

    /**
     * 关闭侧边栏
     */
    public void closeDrawers() {
        drawerLayout.closeDrawer(layoutRightDrawer, true);
    }

    /**
     * 打开侧边栏
     */
    public void openDrawer() {
        drawerLayout.openDrawer(layoutRightDrawer);
    }


    /**
     * 获取上报事件数据
     */
    public void getReportRecord(int pageNum) {
        if (pageNum == 1) {
            currentPage = 1;
        }

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", pageNum);
        hashMap.put("pageSize", Constant.PAGE_SIZE);
        hashMap.put("name", checkName);
        hashMap.put("beginTime", beginTime);
        hashMap.put("endTime", endTime);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_REPORT_RECORD_ALL)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                AllReportRecordBean allReportRecord = new AllReportRecordBean();
                                allReportRecord = gson.fromJson(result, AllReportRecordBean.class);

                                AllReportRecordBean.DataBean dataBean = allReportRecord.getData();
                                List<AllReportRecordBean.DataBean.ListBean> listBeans = dataBean.getList();
                                try {
                                    if (listBeans != null) {
                                        isLoadMore = listBeans.size() > 0 && listBeans.size() % Constant.PAGE_SIZE == 0 ? true : false;
                                        //当是第一页的时候先清空数组，防止下拉操作的时候加载重复数据
                                        if (currentPage == 1) {
                                            allRecordReportAdapter.replaceData(listBeans);
                                        } else {
                                            allRecordReportAdapter.addData(listBeans);
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                isLoadMore = false;
                                ToastUtils.showLong(getResources().getString(com.mingtu.center.R.string.text_json_error));
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);

                    }
                });
    }

    /**
     * 获得上报事件的部门名字数据
     */
    private void getDeptList2() {
        OkGo.<String>post(Constant.getInstance().POST_DEPT_LIST2)
                .tag(this)
                .upJson("")
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                deptNameBean2 = new DeptNameBean();
                                deptNameBean2 = gson.fromJson(result, DeptNameBean.class);

                                if (deptNameBean2 != null) {
                                    departBeans2 = deptNameBean2.getList();

                                    if (departBeans2 != null) {
                                        if (departBeans2.size() > 0) {
                                            if (departBeans2.size() > 6) {
                                                //数据大于6的时候，取前6条数据，有展开收回操作
                                                myDepartBeans2 = departBeans2.subList(0, 6);
                                                leaderDepartmentAdapter.upData(myDepartBeans2);
                                                layoutArrowDepart2.setVisibility(View.VISIBLE);

                                            } else {
                                                //数据个数小与6的时候，展开视图隐藏
                                                leaderDepartmentAdapter.upData(departBeans2);
                                                layoutArrowDepart2.setVisibility(View.GONE);
                                            }

                                            //默认加载第一个保护站的员工
                                            String defaultDeptId = deptNameBean2.getList().get(0).getDeptId() + "";
                                            getPeopleList(defaultDeptId);
                                        }
                                    }

                                }


                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }

                        }
                    }
                });
    }

    /**
     * 获得部门下面的人员数据
     */
    private void getPeopleList(String deptId) {

        OkGo.<String>get(Constant.getInstance().GET_DEPART_PEOPLE)
                .tag(this)
                .params("deptId", deptId)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                DepartStaffBean departStaffBean = new DepartStaffBean();
                                departStaffBean = gson.fromJson(result, DepartStaffBean.class);
                                departStaffBeans = departStaffBean.getList();

                                if (departStaffBeans != null) {
                                    if (departStaffBeans.size() > 0) {

                                        if (departStaffBeans.size() > 12) {
                                            myDepartStaffBeans = departStaffBeans.subList(0, 12);
                                            departStaffAdapter.upData(myDepartStaffBeans);
                                            layoutArrowPeople.setVisibility(View.VISIBLE);
                                        } else {
                                            departStaffAdapter.upData(departStaffBeans);
                                            layoutArrowPeople.setVisibility(View.GONE);
                                        }


                                    }
                                }
                            } catch (JsonSyntaxException e) {

                                ToastUtils.showLong(getResources().getString(com.mingtu.center.R.string.text_json_error));
                            }


                        }
                    }
                });
    }

}